package com.heima.datasync.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * 数据初始化,将article数据库中文章详情存入es
 */
@Service
public class EsDataServiceImpl implements EsDataService {

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * sql中数据库
     * @return
     */
    @Override
    public ResponseResult dataInit() {
        //1.查询article数据库中所有的article数据
        List<ApArticle> apArticles = apArticleMapper.findAllArticles();

         if(apArticles==null || apArticles.size()==0){
             return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"无查询到的文章数据");
         }

        //2.把article数据封装为vo对象, 导入es索引库中
        BulkRequest bulkRequest = new BulkRequest("app_info_article"); //指定索引库名称

         //ES操作三步走
            //2.1 创建批量导入请求
        // 高可用需求  ***批量导入的请求 不适合一次性导入特别多的文档，建议导入文章的数量  1000 ~ 2000 文档,可设置分页导入
        apArticles.stream().map(apArticle -> {
            SearchArticleVo searchArticleVo = new SearchArticleVo();
            BeanUtils.copyProperties(apArticle,searchArticleVo);
            return searchArticleVo;
        }).forEach(vo -> {
                //遍历每一个Vo对象,构建添加文档的请求
            IndexRequest request = new IndexRequest();
            request.id(String.valueOf(vo.getId()));                         // 设置文档ID
            request.source(JSON.toJSONString(vo), XContentType.JSON);       // 设置文档内容,把vo对象转为字符串
            bulkRequest.add(request);
        });
            //2.2 客户端执行批量导入请求
        try {
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"批量导入出现异常");
        }
        return ResponseResult.okResult();
    }
}
